package com.wanglei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.wanglei.constants.SystemConstants;
import com.wanglei.domain.entity.LoginUser;
import com.wanglei.domain.entity.User;
import com.wanglei.mapper.MenuMapper;
import com.wanglei.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user=null;
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUserName,username)
                .eq(User::getStatus, SystemConstants.USER_STATUS_NORMAL);
        //User user = userMapper.selectOne(queryWrapper); //这样写获取不到id
        Optional<User> userOptional = Optional.ofNullable(userMapper.selectOne(queryWrapper));//获取到id写法
        if (userOptional.isPresent()){
            user = userOptional.get();
        }
        System.out.println("id--------:"+user.getId());
        if (Objects.isNull(user)){//数据库没有用户名，认证失败
            throw new UsernameNotFoundException("用户名不存在！！！");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中 授权
//        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
        List<String> permissionKeyList = menuMapper.selectPermsByUserId(user.getId());

        //封装成UserDetails对象返回
        return new LoginUser(user,permissionKeyList);
    }
}
